import { createRouter, createWebHashHistory } from "vue-router";
import Layout from "@/layout/Layout.vue";
import request from "@/utils/request";
import UserLayout from "@/layout/user/Layout.vue";

const routes = [

  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/Register"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});


// 在刷新页面的时候重置当前路由

const userStr = sessionStorage.getItem("user");
  if (userStr) {
    const user = JSON.parse(userStr);
    if (user && user.roleDescribe.includes("管理员")) {
      resetRouter();
    } else {
      resetUserRouter();
    }
  }

function resetRouter() {
  const userStr = sessionStorage.getItem("user");
  if (userStr) {
    const user = JSON.parse(userStr);
    let root = {
      path: "/",
      name: "Layout",
      component: Layout,
      redirect: "/home",
      children: [],
    };
    user.permissions.forEach((p) => {
      
      let obj = {
        path: p.path,
        name: p.permissionName,
        component: () => import("@/views/" + p.permissionName),
      };
      root.children.push(obj);
    });
    if (router) {
      router.addRoute(root);
    }
  }
}
function resetUserRouter() {
  const userStr = sessionStorage.getItem("user");
  if (userStr) {
    const user = JSON.parse(userStr);
    let root = {
      path: "/user",
      name: "UserLayout",
      component: UserLayout,
      redirect: "/user/home",
      children: [],
    };
    //动态处理权限路径路由
    user.permissions.forEach((p) => {
      if (p.path === "/postExamManage") {
        p.path = "/user/postExamManage";
      }
      let obj = {
        path: p.path,
        name: "User" + p.permissionName,
        component: () => import("@/views/user/" + p.permissionName),
      };
      root.children.push(obj);
    });
    if (router) {
      router.addRoute(root);
    }
  }
    
}

//路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === "/login" || to.path === "/register") {
    //放行

    next();
    return;
  }
  let user = sessionStorage.getItem("user")
    ? JSON.parse(sessionStorage.getItem("user"))
    : {};
  if (!user.permissions || !user.permissions.length) {
    next("/login");
  } else if (!user.permissions.find((p) => {
    if (to.path === "/user/postExamManage") {
      to.path = "/postExamManage";
    }
    return p.path === to.path
  })) {
    next("/login");
  } else {
    next();
  }
});

export default router;
